<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="70vw">
    <el-form size="large" ref="formRef" :model="formData" :rules="formRules" label-width="100px"
      v-loading="formLoading">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="设备编码" prop="code">
            <el-input v-model="formData.code" placeholder="请输入设备编码" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="设备名称" prop="equipmentName">
            <el-input v-model="formData.equipmentName" placeholder="请输入设备名称" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="所属部门" prop="deptId">
            <el-tree-select v-model="formData.deptId" :data="deptTree" :props="defaultProps" check-strictly
              default-expand-all placeholder="请选择所属部门" value-key="deptId" />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="8">
          <el-form-item label="维护人" prop="dutyUserId">
            <el-select clearable multiple filterable v-model="formData.maintenanceUserId" placeholder="请选择责任人,支持模糊搜索">
              <el-option v-for="dict in userList" :key="dict.id" :label="dict.nickname" :value="dict.id" />
            </el-select>
          </el-form-item>
        </el-col> -->
        <el-col :span="8">
          <el-form-item label="设备分类" prop="equipmentClassify">
            <el-select filterable v-model="formData.equipmentClassify" placeholder="请选择设备分类" style="width: 100%;">
              <el-option v-for="dict in equipmentClassify" :key="dict.id" :label="dict.name" :value="dict.id" />
            </el-select>
          </el-form-item>
        </el-col>

        <!-- 第二行 -->
        <el-col :span="8">
          <el-form-item label="设备状态" prop="equipmentStatus">
            <el-select v-model="formData.equipmentStatus" placeholder="请选择设备状态" style="width: 100%;">
              <el-option v-for="dict in getIntDictOptions(DICT_TYPE.EQUIPMENT_STATUS)" :key="dict.value"
                :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="设备类型" prop="equipmentType">
            <el-select v-model="formData.equipmentType" placeholder="请选择设备类型" style="width: 100%;">
              <el-option v-for="dict in getIntDictOptions(DICT_TYPE.EQUIPMENT_TYPE)" :key="dict.value"
                :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="规格型号" prop="equipmentModel">
            <el-input v-model="formData.equipmentModel" placeholder="请输入规格型号" />
          </el-form-item>
        </el-col>

        <!-- 第三行 -->
        <el-col :span="8">
          <el-form-item label="设备功率(KW)" prop="equipmentPower">
            <el-input v-model="formData.equipmentPower" placeholder="请输入设备功率kw" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="设备重量(KG)" prop="equipmentWeight">
            <el-input v-model="formData.equipmentWeight" placeholder="请输入设备重量" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="设备吨位" prop="equipmentTonnage">
            <el-input v-model="formData.equipmentTonnage" placeholder="请输入设备吨位" />
          </el-form-item>
        </el-col>

        <!-- 第四行 -->
        <el-col :span="8">
          <el-form-item label="安装位置" prop="installPosition">
            <el-input v-model="formData.installPosition" placeholder="请输入安装位置" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="安装日期" prop="installDate">
            <el-date-picker v-model="formData.installDate" type="date" value-format="YYYY-MM-DD" placeholder="选择安装日期"
              style="width: 100%;" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="投产日期" prop="productionDate">
            <el-date-picker v-model="formData.productionDate" type="date" value-format="YYYY-MM-DD" placeholder="选择投产日期"
              style="width: 100%;" />
          </el-form-item>
        </el-col>

        <!-- 第五行 -->
        <el-col :span="8">
          <el-form-item label="单位" prop="unit">
            <el-input v-model="formData.unit" placeholder="请输入单位" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="设备厂家" prop="equipmentProducer">
            <el-input v-model="formData.equipmentProducer" placeholder="请输入设备厂家" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="联系人" prop="contacts">
            <el-input v-model="formData.contacts" placeholder="请输入联系人" />
          </el-form-item>
        </el-col>

        <!-- 第六行 -->
        <el-col :span="8">
          <el-form-item label="联系电话" prop="contactsNumber">
            <el-input v-model="formData.contactsNumber" placeholder="请输入联系电话" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="使用状态" prop="useType">
            <el-select v-model="formData.useType" placeholder="请选择使用状态" style="width: 100%;">
              <el-option v-for="dict in getIntDictOptions(DICT_TYPE.USED_TYPE)" :key="dict.value" :label="dict.label"
                :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="最近一次保养时间" prop="maintainDatetime" label-width="100px">
            <el-date-picker v-model="formData.maintainDatetime" type="datetime" value-format="x"
              placeholder="选择最近一次保养时间" style="width: 100%;" />
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="下次保养时间" prop="nextMaintainDatetime" label-width="100px">
            <el-date-picker disabled v-model="formData.nextMaintainDatetime" type="datetime" value-format="x"
              placeholder="选择下次保养时间" style="width: 100%;" />
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="最近一次维护时间" prop="lastMaintainTimeDamage" label-width="100px">
            <el-date-picker v-model="formData.lastMaintainTimeDamage" type="datetime" value-format="x"
              placeholder="选择最近一次维护时间" style="width: 100%;" />
          </el-form-item>
        </el-col>


        <!-- 备注占一整行 -->
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="formData.remark" type="textarea" placeholder="请输入备注" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { EquipmentManageApi, EquipmentManage } from '@/api/business/equipmentmanage'
import { defaultProps, handleTree } from '@/utils/tree'
import * as DeptApi from '@/api/system/dept'
import { EquipmentTypeApi } from '@/api/business/equipmenttype'
import * as UserApi from '@/api/system/user'


/** 设备台账 表单 */
defineOptions({ name: 'EquipmentManageForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  code: undefined,
  equipmentName: undefined,
  deptId: undefined,
  equipmentClassify: undefined,
  equipmentStatus: undefined,
  equipmentType: undefined,
  equipmentModel: undefined,
  equipmentPower: undefined,
  equipmentWeight: undefined,
  equipmentTonnage: undefined,
  installPosition: undefined,
  installDate: undefined,
  productionDate: undefined,
  unit: undefined,
  equipmentProducer: undefined,
  contacts: undefined,
  contactsNumber: undefined,
  useType: undefined,
  maintainDatetime: undefined,
  remark: undefined,
  nextMaintainDatetime: undefined,
  maintenanceUserId: [],
  lastMaintainTimeDamage: undefined,


})
const formRules = reactive({
  code: [{ required: true, message: '设备编码不能为空', trigger: 'blur' }],
  equipmentName: [{ required: true, message: '设备名称不能为空', trigger: 'blur' }],
  deptId: [{ required: true, message: '所属部门不能为空', trigger: 'blur' }],
  equipmentClassify: [{ required: true, message: '设备分类不能为空', trigger: 'blur' }],
  equipmentStatus: [{ required: true, message: '设备状态不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref
const deptTree = ref() // 树形结构
const equipmentClassify = ref([]) // 树形结构

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  getTree()//获取部门数据
  getTypeList()
  await initData()
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await EquipmentManageApi.getEquipmentManage(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗


/** 获得部门树 */
const getTree = async () => {
  deptTree.value = []
  const data = await DeptApi.getSimpleDeptList()
  let dept: Tree = { id: 0, name: '顶级部门', children: [] }
  dept.children = handleTree(data)
  deptTree.value.push(dept)
}

//获取所有分类
const getTypeList = async () => {
  const res = await EquipmentTypeApi.getEquipmentTypeList();
  console.log("list", res);

  equipmentClassify.value = res
}


/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as EquipmentManage
    if (formType.value === 'create') {
      await EquipmentManageApi.createEquipmentManage(data)
      message.success(t('common.createSuccess'))
    } else {
      await EquipmentManageApi.updateEquipmentManage(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}


//用户列表
const userList = ref([])

const initData = async () => {
  userList.value = await UserApi.getSimpleUserList()
}


/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    code: undefined,
    equipmentName: undefined,
    deptId: undefined,
    equipmentClassify: undefined,
    equipmentStatus: undefined,
    equipmentType: undefined,
    equipmentModel: undefined,
    equipmentPower: undefined,
    equipmentWeight: undefined,
    equipmentTonnage: undefined,
    installPosition: undefined,
    installDate: undefined,
    productionDate: undefined,
    unit: undefined,
    equipmentProducer: undefined,
    contacts: undefined,
    contactsNumber: undefined,
    useType: undefined,
    maintainDatetime: undefined,
    remark: undefined,
    nextMaintainDatetime: undefined,
    maintenanceUserId: [],
    lastMaintainTimeDamage: undefined,

  }
  formRef.value?.resetFields()
}
</script>
